<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="设备编号" prop="sn">
        <el-input v-model="queryParams.sn" placeholder="请输入设备编号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="Mac地址" prop="userSn">
        <el-input v-model="queryParams.userSn" placeholder="请输入Mac地址" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="设备状态" prop="deviceStatus">
        <el-select v-model="queryParams.deviceStatus" placeholder="请选择设备状态" clearable style="width: 195px;">
          <el-option v-for="dict in pro_device_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="省份" prop="provinceName">
        <el-input v-model="queryParams.provinceName" placeholder="请输入省份" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="运营商" prop="ispName">
        <!-- <el-input v-model="queryParams.isp" placeholder="请输入运营商id" clearable @keyup.enter="handleQuery" /> -->
        <el-select v-model="queryParams.ispName" placeholder="请选择运营商" clearable style="width: 195px;">
          <el-option v-for="dict in operator_type" :key="dict.value" :label="dict.label" :value="dict.label" />
        </el-select>
      </el-form-item>
      <el-form-item label="设备绑定时间">
        <!-- <el-date-picker clearable v-model="queryParams.bindTime" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择设备绑定时间"></el-date-picker> -->
          <el-date-picker
            v-model="bindTime"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        
      </el-form-item>
      
      <el-form-item>
        <!-- <el-button @click="openFilter = !openFilter">筛选</el-button> -->
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['producer:device:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['producer:device:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['producer:device:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['producer:device:export']">导出</el-button>
      </el-col> -->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="deviceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" fixed="left" />
      <el-table-column label="设备编号" align="left" width="280" prop="sn" v-if="columns[0].visible">
        <template #default="scope">
          <el-row style="text-align: left;">
            <el-col><p class="mx-1" size="medium" style="margin: 0px;">{{ scope.row.sn }}</p></el-col>
            <el-col><p class="mx-1" size="small" style="margin: 0px;">{{ scope.row.userSn }}</p></el-col>
          </el-row>
        </template>
      </el-table-column>
      <!-- <el-table-column label="自定义sn" align="center" width="200" prop="userSn" v-if="columns[1].visible" /> -->
      <!-- <el-table-column label="设备类型" align="center" prop="deviceType" v-if="columns[2].visible" /> -->
      <el-table-column label="设备状态" align="center" prop="deviceStatus" v-if="columns[3].visible">
        <template #default="scope">
          <dict-tag :options="pro_device_status" :value="scope.row.deviceStatus" />
        </template>
      </el-table-column>
      <el-table-column label="省份" align="center" prop="provinceName" v-if="columns[4].visible" width="200"/>
      <el-table-column label="运营商" align="center" prop="ispName" v-if="columns[5].visible"/>
      <el-table-column label="设备绑定时间" align="center" prop="bindTime" width="180" v-if="columns[6].visible">
        <template #default="scope">
          <span>{{scope.row.bindTime }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="单线路承诺带宽/Mbps" align="center" width="190" prop="linePromiseBandWidth"
        v-if="columns[7].visible" /> -->
      <!-- <el-table-column label="承诺线路数" align="center" width="90" prop="promiseLineNum" v-if="columns[8].visible" /> -->
      <el-table-column label="承诺总带宽/Mbps" align="center" width="150" prop="promiseBandWidth"
        v-if="columns[9].visible" />
      <!-- <el-table-column label="内网ip" align="center" prop="inIp" v-if="columns[10].visible" width="150" />
      <el-table-column label="外网ip" align="center" prop="outIp" v-if="columns[11].visible" width="150" />
      <el-table-column label="mac地址" align="center" prop="macAddr" v-if="columns[12].visible" width="180" /> -->
      <el-table-column label="nat类型" align="center" prop="natName" v-if="columns[13].visible" width="120" />
      <el-table-column label="upnp" align="center" prop="upnp" v-if="columns[14].visible" width="100" />
      <!-- <el-table-column label="基础ping丢包" align="center" prop="basicPingPacketLoss" v-if="columns[15].visible"
        width="105" /> -->
      <!-- <el-table-column label="基础ping时延" align="center" prop="basicPingAvgRtt" v-if="columns[16].visible" width="105" /> -->
      <el-table-column label="定向业务" align="center" prop="bizName" v-if="columns[17].visible" width="105" />
      <!-- <el-table-column label="定向业务名字" align="center" prop="bizName" v-if="columns[18].visible" width="105" /> -->
      <el-table-column label="业务状态" align="center" prop="bizResult" v-if="columns[19].visible" width="105" />
      <!-- <el-table-column label="定向业务结果" align="center" prop="bizResult" v-if="columns[20].visible" width="105" /> -->
      <!-- <el-table-column label="定向业务报名状态" align="center" prop="applyStatus" v-if="columns[21].visible" width="135" /> -->
      <!-- <el-table-column label="定向业务报名结果" align="center" prop="applyResult" v-if="columns[22].visible" width="135" /> -->
      <!-- <el-table-column label="自定义字段" align="center" prop="extra" v-if="columns[23].visible" width="90" /> -->
      <el-table-column label="版本" align="center" prop="version" v-if="columns[24].visible" />
      <!-- <el-table-column label="网络压测结果" align="center" prop="netPressResult" v-if="columns[25].visible" width="245" /> -->
      <el-table-column label="标签信息" align="center" prop="tagList" v-if="columns[26].visible" width="230">
        <template #default="scope">
          <el-tag v-for="item in scope.row.tagList" :key="item" class="mx-1" type="success" style="margin: 3px;">{{ item.tagValue }}</el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column label="备注" align="center" prop="remark" v-if="columns[27].visible" /> -->
      <el-table-column label="渠道" align="center" prop="channel" v-if="columns[28].visible" width="100" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="auto">
        <template #default="scope">
          <el-button link type="primary" @click="handleInfo(scope.row)">详情</el-button>
          <el-button link type="danger" @click="handleUnbind(scope.row)">解绑</el-button>
          <!-- <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['producer:device:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['producer:device:remove']">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改设备信息对话框 -->
    <el-dialog :title="title" v-model="open" width="50vw" append-to-body :destroyOnClose="true">
      <el-form ref="deviceRef" :model="form" :rules="rules">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备编号" prop="sn">
              <el-input v-model="form.sn" placeholder="请输入设备编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="自定义sn" prop="userSn">
              <el-input v-model="form.userSn" placeholder="请输入自定义sn" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备状态" prop="deviceStatus">
              <el-select v-model="form.deviceStatus" placeholder="请选择设备状态">
                <el-option v-for="dict in pro_device_status" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="省份id" prop="province">
              <el-input v-model="form.province" placeholder="请输入省份id" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="运营商id" prop="isp">
              <el-input v-model="form.isp" placeholder="请输入运营商id" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备绑定时间" prop="bindTime">
              <el-date-picker clearable v-model="form.bindTime" type="date" value-format="YYYY-MM-DD"
                placeholder="请选择设备绑定时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单线路承诺带宽/Mbps" prop="linePromiseBandWidth">
              <el-input v-model="form.linePromiseBandWidth" placeholder="请输入单线路承诺带宽/Mbps" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="承诺线路数" prop="promiseLineNum">
              <el-input v-model="form.promiseLineNum" placeholder="请输入承诺线路数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="承诺总带宽/Mbps" prop="promiseBandWidth">
              <el-input v-model="form.promiseBandWidth" placeholder="请输入承诺总带宽/Mbps" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="内网ip" prop="inIp">
              <el-input v-model="form.inIp" placeholder="请输入内网ip" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="外网ip" prop="outIp">
              <el-input v-model="form.outIp" placeholder="请输入外网ip" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="mac地址" prop="macAddr">
              <el-input v-model="form.macAddr" placeholder="请输入mac地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="upnp" prop="upnp">
              <el-input v-model="form.upnp" placeholder="请输入upnp" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="基础ping丢包" prop="basicPingPacketLoss">
              <el-input v-model="form.basicPingPacketLoss" placeholder="请输入基础ping丢包" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="基础ping时延" prop="basicPingAvgRtt">
              <el-input v-model="form.basicPingAvgRtt" placeholder="请输入基础ping时延" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="定向业务id" prop="bizId">
              <el-input v-model="form.bizId" placeholder="请输入定向业务id" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="定向业务名字" prop="bizName">
              <el-input v-model="form.bizName" placeholder="请输入定向业务名字" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="定向业务结果" prop="bizResult">
              <el-input v-model="form.bizResult" placeholder="请输入定向业务结果" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="定向业务报名结果" prop="applyResult">
              <el-input v-model="form.applyResult" placeholder="请输入定向业务报名结果" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="自定义字段" prop="extra">
              <el-input v-model="form.extra" placeholder="请输入自定义字段" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="版本" prop="version">
              <el-input v-model="form.version" placeholder="请输入版本" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="网络压测结果" prop="netPressResult">
              <el-input v-model="form.netPressResult" placeholder="请输入网络压测结果" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="标签信息" prop="tagList">
              <el-input v-model="form.tagList" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="渠道" prop="channel">
              <el-input v-model="form.channel" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 详情 -->
    <el-drawer v-model="openDrawer" title="设备详情" size="60%" :destroyOnClose="true">
      <div class="detail-container">
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="detail-item">
              <div class="detail-label">SN:</div>
              <div class="detail-content">
                <div>
                  <p>{{ formDrawer.userSn }}</p>
                  <p>{{ formDrawer.sn }}</p>
                </div>
              </div>
            </div>
          </el-col>

          <el-col :span="8">
            <div class="detail-item">
              <div class="detail-label">省份:</div>
              <div class="detail-content">
                <p>{{ formDrawer.provinceName }}</p>
              </div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-item">
              <div class="detail-label">运营商:</div>
              <div class="detail-content">
                <p>{{ formDrawer.ispName }}</p>
              </div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-item">
              <div class="detail-label">设备状态:</div>
              <div class="detail-content">
                <p v-if="formDrawer.deviceStatus === 1">在线</p>
                <p v-if="formDrawer.deviceStatus === 0">离线</p>
              </div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-item">
              <div class="detail-label">备注:</div>
              <div class="detail-content">
                <p>{{ formDrawer.bindTime }}</p>
              </div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-item">
              <div class="detail-label">设备标签:</div>
              <div class="detail-content">
                <div v-show="formDrawer.tagList && formDrawer.tagList.length > 0"
                  style="font-size: 12px;line-height: 20px;">
                  {{ formDrawer.tagListname }}
                </div>
                <el-button type="primary" @click="editTags" link>修改</el-button>
              </div>
            </div>
          </el-col>
        </el-row>
        <el-drawer v-model="openTags" title="设备标签设置" direction="rtl" :destroyOnClose="true" @close="closeTags">
          <div class="device-tag-setting">
            <!-- 顶部须知 -->
            <div class="top-alert">
              <div class="header-tip">
                <b>须知：</b>
                <p>1、开启设备标签时，<span class="red">需要关注当前业务是否支持此标签</span>，如业务不支持，强行开启标签会导致0跑！</p>
                <p>2、开启日间、晚间峰调度等标签，可能会导致利用率降低(10%~15%左右)，请谨慎开启。</p>
              </div>
            </div>

            <el-form label-width="100px" class="form" label-position="top">
              <el-form-item label="调度范围">
                <el-select v-model="scope" placeholder="不限范围" style="width: 100%;" @change="handleScopeChange">
                  <!-- <el-option label="不限范围" :value="2" />
                  <el-option label="同省调度" value="intra_provincial" /> -->
                  <el-option v-for="item in scopeAry" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>

              <el-form-item label="调度时段">
                <el-select ref="periodRef" v-model="period" placeholder="请选择" style="width: 100%;"
                  @change="handlePeriodChange">
                  <!-- <el-option label="不限时段" :value="2" />
                  <el-option label="纯跑晚高峰" value="evening_peak" />
                  <el-option label="纯跑午晚高峰" value="noon_peak" /> -->
                  <el-option v-for="item in periodAry" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>

              <el-form-item label="纯跑IPv6">
                <!-- 这里写表单的提示信息 -->
                <template #label>
                  <span>纯跑IPv6</span>

                </template>
                <el-select v-model="ipv6" placeholder="请选择" style="width: 100%;" @change="handleIpv6Change">
                  <!-- <el-option label="关闭" :value="2" />
                  <el-option label="开启" :value="1" /> -->
                  <el-option v-for="item in ipv6Ary" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>

              <el-form-item label="异网支付">
                <el-select v-model="pay" multiple placeholder="请选择" style="width: 340px" @change="handlePayChange()"
                  @remove-tag="removePayTag">
                  <!-- <el-option label="交付电信" value="mix_isp_1" />
                  <el-option label="交付联通" value="mix_isp_2" />
                  <el-option label="交付移动" value="mix_isp_5" /> -->
                  <el-option v-for="item in payAry" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-form>
          </div>
        </el-drawer>
      </div>

      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane label="收益" name="first">
          <IncomeTrendPanel v-if="activeName === 'first' && openDrawer" :formDrawer="formDrawer"
            :activeName="activeName" />
        </el-tab-pane>
        <el-tab-pane label="带宽" name="second">
          <BandwidthTrendPanel v-if="activeName === 'second' && openDrawer" :formDrawer="formDrawer"
            :activeName="activeName" />
        </el-tab-pane>
        <!-- <el-tab-pane label="质量监控" name="third">
          <div>
            <el-button-group>
              <el-button :type="qualityTabDate === 'today' ? 'primary' : 'default'" size="small"
                @click="qualityTabDate = 'today'">今天</el-button>
              <el-button :type="qualityTabDate === 'yesterday' ? 'primary' : 'default'" size="small"
                @click="qualityTabDate = 'yesterday'">昨天</el-button>
            </el-button-group>
            <el-tabs v-model="qualitySubTab" style="margin-top: 16px;">
              <el-tab-pane label="网络" name="network">
                <QualityNetworkCharts v-if="qualitySubTab === 'network' && activeName === 'third' && openDrawer" :formDrawer="formDrawer" />
              </el-tab-pane>
              <el-tab-pane label="内存" name="memory">
                <div style="color: #aaa; padding: 32px 0;">暂无数据</div>
              </el-tab-pane>
            </el-tabs>
            </div>
        </el-tab-pane> -->
        <el-tab-pane label="网络信息" name="fourth">
          <NetworkInfoPanel v-if="activeName === 'fourth' && openDrawer" :formDrawer="formDrawer"
            :activeName="activeName" @getFetchDeviceDetail="getFetchDeviceDetail"/>
        </el-tab-pane>
        <el-tab-pane label="硬件信息" name="fifth">
          <HardwareInfoPanel v-if="activeName === 'fifth' && openDrawer" :formDrawer="formDrawer"
            :activeName="activeName" />
        </el-tab-pane>
      </el-tabs>
    </el-drawer>
  </div>
</template>

<script setup name="Device">
import { listDevice, getDevice, delDevice, addDevice, updateDevice, incomeTrend, updateDeviceTag, getDeviceDetail, unbindDevice } from "@/api/producer/device"
import IncomeTrendPanel from './components/IncomeTrendPanel.vue'
import BandwidthTrendPanel from './components/BandwidthTrendPanel.vue'
import QualityNetworkCharts from './components/QualityNetworkCharts.vue'
import NetworkInfoPanel from './components/NetworkInfoPanel.vue'
import HardwareInfoPanel from './components/HardwareInfoPanel.vue'
import { ref, nextTick } from "vue"

const { proxy } = getCurrentInstance()
const { pro_device_status, operator_type } = proxy.useDict('pro_device_status', 'operator_type')

const deviceList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const openFilter = ref(false)
const openDrawer = ref(false)
const activeName = ref('first')


// 质量监控
const qualityTabDate = ref('today')
const qualitySubTab = ref('network')

const openTags = ref(false)

const scope = ref({ label: '不限范围', value: 2 })
const period = ref({ label: '不限时段', value: 'none_time' })
const pay = ref([])
const ipv6 = ref('')

const skipPayChange = ref(false)
const skipStr = ref(0)
const bindTime = ref([])

// const scopeAry = ref([
//   { label: '不限范围', value: 2 },
//   { label: '同省调度', value: 'intra_provincial' }
// ])
const periodAry = ref([
  { label: '不限时段', value: 'none_time' },
  { label: '纯跑晚高峰', value: 'evening_peak' },
  { label: '纯跑午晚高峰', value: 'noon_peak' }
])
const ipv6Ary = ref([
  { label: '关闭', value: 2 },
  { label: '开启', value: 'internet_ipv6' }
])
const payAry = ref([
  { label: '交付电信', value: 'mix_isp_1' },
  { label: '交付联通', value: 'mix_isp_2' },
  { label: '交付移动', value: 'mix_isp_5' },
])



// 列显隐信息
const columns = ref([
  { key: 0, label: `设备编号`, visible: true },
  { key: 1, label: `Mac地址`, visible: true },
  { key: 2, label: `设备类型`, visible: true },
  { key: 3, label: `设备状态`, visible: true },
  { key: 4, label: `省份id`, visible: true },
  { key: 5, label: `运营商id`, visible: true },
  { key: 6, label: `设备绑定时间`, visible: true },
  { key: 7, label: `单线路承诺带宽/Mbps`, visible: true },
  { key: 8, label: `承诺线路数`, visible: true },
  { key: 9, label: `承诺总带宽/Mbps`, visible: true },
  { key: 10, label: `内网ip`, visible: true },
  { key: 11, label: `外网ip`, visible: true },
  { key: 12, label: `mac地址`, visible: true },
  { key: 13, label: `nat类型id`, visible: true },
  { key: 14, label: `upnp`, visible: true },
  { key: 15, label: `基础ping丢包`, visible: true },
  { key: 16, label: `基础ping时延`, visible: true },
  { key: 17, label: `定向业务id`, visible: true },
  { key: 18, label: `定向业务名字`, visible: true },
  { key: 19, label: `定向业务状态`, visible: true },
  { key: 20, label: `定向业务结果`, visible: true },
  { key: 21, label: `定向业务报名状态`, visible: true },
  { key: 22, label: `定向业务报名结果`, visible: true },
  { key: 23, label: `自定义字段`, visible: true },
  { key: 24, label: `版本`, visible: true },
  { key: 25, label: `网络压测结果`, visible: true },
  { key: 26, label: `标签信息`, visible: true },
  { key: 27, label: `备注`, visible: true },
  { key: 28, label: `渠道`, visible: true },
])

const data = reactive({
  form: {},
  formDrawer: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    sn: null,
    userSn: null,
    deviceType: null,
    deviceStatus: null,
    provinceName: null,
    ispName: null,
    bindTime: null,
    linePromiseBandWidth: null,
    promiseLineNum: null,
    promiseBandWidth: null,
    inIp: null,
    outIp: null,
    macAddr: null,
    natType: null,
    upnp: null,
    basicPingPacketLoss: null,
    basicPingAvgRtt: null,
    bizId: null,
    bizName: null,
    bizStatus: null,
    bizResult: null,
    applyStatus: null,
    applyResult: null,
    extra: null,
    version: null,
    netPressResult: null,
    tagList: null,
    channel: null
  },
  rules: {},
  ProvinceMap: {
  "0": "未知",
  "1": "北京市",
  "2": "上海市",
  "3": "天津市",
  "4": "重庆市",
  "5": "云南省",
  "6": "台湾省",
  "7": "吉林省",
  "8": "四川省",
  "9": "安徽省",
  "10": "山东省",
  "11": "山西省",
  "12": "广东省",
  "13": "江苏省",
  "14": "江西省",
  "15": "河北省",
  "16": "河南省",
  "17": "浙江省",
  "18": "海南省",
  "19": "湖北省",
  "20": "湖南省",
  "21": "甘肃省",
  "22": "福建省",
  "23": "贵州省",
  "24": "辽宁省",
  "25": "陕西省",
  "26": "青海省",
  "27": "黑龙江省",
  "28": "西藏",
  "29": "广西",
  "30": "新疆",
  "31": "宁夏",
  "32": "内蒙古",
  "33": "香港",
  "34": "澳门"
},
ISP: {
  "1": "电信",
	"2": "联通",
	"5": "移动"
},
  tagsParams: {
    sn: null,
    tagName: null,
    tagStatus: null,
    tagValue: null,
  },
  scopeAry: [
    { label: '不限范围', value: 2 },
    { label: '同省调度', value: 'intra_provincial' }
  ]
})

const { queryParams, form, rules, ProvinceMap, ISP, formDrawer, tagsParams, scopeAry } = toRefs(data)

onMounted(() => {
  console.log(operator_type, 'operator_type')
})

// 调度范围
function handleScopeChange() {
  if (scope.value == '2') {
    tagsParams.value.sn = formDrawer.value.sn;
    tagsParams.value.tagName = "intra_provincial";
    tagsParams.value.tagStatus = scope.value;
    tagsParams.value.tagValue = "同省调度";
  } else {
    tagsParams.value.sn = formDrawer.value.sn;
    tagsParams.value.tagName = scope.value;
    tagsParams.value.tagStatus = "1";
    tagsParams.value.tagValue = "同省调度";
  }

  updateDeviceTag(tagsParams.value).then(response => {
    if (response.code === 200) {
      proxy.$modal.msgSuccess("操作成功")
      // openTags.value = false
      getFetchDeviceDetail()
    }
  })
}

// 调度时段
function handlePeriodChange() {
  console.log(period.value, '调度时段')
  
  let oldValue = proxy.$refs.periodRef.modelValue
  const newValue = period.value
  // 处理oldValue是字符串还是对象
  if (typeof oldValue === 'string') {
    oldValue = periodAry.value.find(item => item.value === oldValue) || { value: oldValue, label: oldValue }
  }

  // 这里根据当前newValue或者oldValue的值过滤出对应的对象
  const oldValueItem = periodAry.value.find(item => item.value === oldValue.value)
  const newValueItem = periodAry.value.find(item => item.value === newValue)
  
  // 规则1: 旧值是none_time时，只调新增接口
  if (oldValue.value === 'none_time') {
    if (newValue.value !== 'none_time') {
      addPeriodTag(newValueItem)
    }
    return
  }
  
  // 规则2: 新值是none_time时，只调删除接口
  if (newValue.value === 'none_time') {
    deletePeriodTag(oldValueItem)
    return
  }

  
  // 规则3: 两个值都不是none_time时，先删除旧值再新增
  if (oldValue.value !== 'none_time' && newValue.value !== 'none_time') {
    deletePeriodTag(oldValueItem)
    //这里判断newValue不是字符串类型，且不等于none_time，则调用addPeriodTag函数
    if (typeof newValueItem !== 'string' && newValueItem.value !== 'none_time') {
      setTimeout(() => addPeriodTag(newValueItem), 1000)
    }
    
  }
}

// 新增时段标签
function addPeriodTag(periodItem) {
  nextTick(() => {
      tagsParams.value.sn = formDrawer.value.sn
      tagsParams.value.tagName = periodItem.value
      tagsParams.value.tagStatus = "1"
      tagsParams.value.tagValue = periodItem.label
      
      return updateDeviceTag(tagsParams.value).then(response => {
        if (response.code === 200) {
          proxy.$modal.msgSuccess("操作成功")
          getFetchDeviceDetail()
        }
      })

  })
}

// 删除时段标签
function deletePeriodTag(periodItem) {
  nextTick(() => {
    tagsParams.value.sn = formDrawer.value.sn
    tagsParams.value.tagName = periodItem.value
    tagsParams.value.tagStatus = "2"
    tagsParams.value.tagValue = periodItem.label
    
    return updateDeviceTag(tagsParams.value).then(response => {
      if (response.code === 200) {
        proxy.$modal.msgSuccess("操作成功")
        getFetchDeviceDetail()
      }
    })
  })
}

// ipv6纯跑
function handleIpv6Change() {
  if (ipv6.value == '2') {
    tagsParams.value.sn = formDrawer.value.sn;
    tagsParams.value.tagName = "internet_ipv6";
    tagsParams.value.tagStatus = ipv6.value;
    tagsParams.value.tagValue = "ipv6纯跑";
  } else {
    tagsParams.value.sn = formDrawer.value.sn;
    tagsParams.value.tagName = "internet_ipv6";
    tagsParams.value.tagStatus = "1";
    tagsParams.value.tagValue = "ipv6纯跑";
  }

  updateDeviceTag(tagsParams.value).then(response => {
    if (response.code === 200) {
      proxy.$modal.msgSuccess("操作成功")
      getFetchDeviceDetail()
    }
  })
}

// 异网支付
function handlePayChange(value, str) {
  console.log(value, str, '异网支付-新增')
  console.log(skipStr.value, 'skipStr.value')
  nextTick(() => {

    if (skipStr.value == 0) {
      console.log('执行添加')
      let newPay = null;
      if (pay.value.length > 0) {
        newPay = [pay.value[pay.value.length - 1]]

        let name = null;
        if (newPay == 'mix_isp_1') {
          name = "交付电信";
        } else if (newPay == 'mix_isp_2') {
          name = "交付联通";
        } else if (newPay == 'mix_isp_5') {
          name = "交付移动";
        }

        tagsParams.value.sn = formDrawer.value.sn;
        tagsParams.value.tagName = newPay[0];
        tagsParams.value.tagStatus = "1";
        tagsParams.value.tagValue = name;

        updateDeviceTag(tagsParams.value).then(response => {
          if (response.code === 200) {
            proxy.$modal.msgSuccess("操作成功")
            getFetchDeviceDetail()
          }
        })
      }
    }
  })
}

function closeTags() {
  console.log('关闭')
  pay.value = []
}


function removePayTag(oldvalue) {
  console.log(oldvalue, '执行移除')
  skipPayChange.value = true
  skipStr.value += 1
  if (typeof oldvalue === 'string') {
    oldvalue = payAry.value.find(item => item.value === oldvalue) || { value: oldvalue, label: oldvalue }
  }
  let newValue = payAry.value.find(item => item.value == oldvalue.value)
  console.log(newValue, '过滤的值--异网支付删除')

  let name = null;
  if (oldvalue == 'mix_isp_1') {
    name = "交付电信";
  } else if (oldvalue == 'mix_isp_2') {
    name = "交付联通";
  } else if (oldvalue == 'mix_isp_5') {
    name = "交付移动";
  }
      tagsParams.value.sn = formDrawer.value.sn;
      tagsParams.value.tagName = newValue.value;
      tagsParams.value.tagStatus = "2";
      tagsParams.value.tagValue = newValue.label;

      updateDeviceTag(tagsParams.value).then(response => {
        if (response.code === 200) {
          proxy.$modal.msgSuccess("操作成功")
          skipStr.value = 0
          getFetchDeviceDetail()
          nextTick(() => {
            skipPayChange.value = false
          })
        }
      })    
}


/** 查询设备信息列表 */
function getList() {
  loading.value = true
  listDevice(proxy.addDateRange(queryParams.value, bindTime.value)).then(response => {
    response.rows.forEach(item => {
      item.tagList = JSON.parse(item.tagList)
      item.tagListname = item.tagList.map(item => item.tagName).join(',')
    })
    deviceList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    sn: null,
    userSn: null,
    deviceType: null,
    deviceStatus: null,
    province: null,
    isp: null,
    bindTime: null,
    linePromiseBandWidth: null,
    promiseLineNum: null,
    promiseBandWidth: null,
    inIp: null,
    outIp: null,
    macAddr: null,
    natType: null,
    upnp: null,
    basicPingPacketLoss: null,
    basicPingAvgRtt: null,
    bizId: null,
    bizName: null,
    bizStatus: null,
    bizResult: null,
    applyStatus: null,
    applyResult: null,
    extra: null,
    version: null,
    netPressResult: null,
    tagList: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null,
    channel: null
  }
  proxy.resetForm("deviceRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  bindTime.value = []
  handleQuery()
  
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加设备信息"
}

/** 详情按钮操作 */
function handleInfo(row) {
  reset()
  getFetchDeviceDetail(row.id);
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getDevice(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改设备信息"
  })
}

/**
 * 详情tab
 * ***/
const handleClick = (tab, event) => {
  console.log(tab, event)
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["deviceRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateDevice(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addDevice(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除设备信息编号为"' + _ids + '"的数据项？').then(function () {
    return delDevice(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

/** 解绑按钮操作 */
function handleUnbind(row) {
  const deviceSn = row.sn
  proxy.$modal.confirm('是否确认解绑设备编号为"' + deviceSn + '"的设备？').then(function () {
    return unbindDevice(row.id)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("解绑成功")
  }).catch(() => { })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('producer/device/export', {
    ...queryParams.value
  }, `device_${new Date().getTime()}.xlsx`)
}

function getFetchDeviceDetail(id) {
  if (id) {
    getDeviceDetail(id).then(response => {
      response.data.tagList = JSON.parse(response.data.tagList)
      response.data.tagListname = response.data.tagList.map(item => item.tagValue).join(',')
      formDrawer.value = response.data
      openDrawer.value = true;
    })
  } else {
    getDeviceDetail(formDrawer.value.id).then(response => {
      response.data.tagList = JSON.parse(response.data.tagList)
      response.data.tagListname = response.data.tagList.map(item => item.tagValue).join(',')
      formDrawer.value = response.data
      openDrawer.value = true;
    })
  }
}

function editTags() {
  openTags.value = true
  console.log(formDrawer.value)
  // 将formDrawer.value的tagList  回显
  if (formDrawer.value.tagList && formDrawer.value.tagList.length > 0) {
    formDrawer.value.tagList.forEach(item => {

      // 用当前的item去查 scopeAry,periodAry, ipv6Ary, payAry中对应的tagValue
      scopeAry.value.forEach(item1 => {
        if (item1.label == item.tagValue) {
          Object.assign(scope, item1)
        }
      })
      periodAry.value.forEach(item1 => {
        if (item1.label == item.tagValue) {
          Object.assign(period, item1)
        }
      })
      ipv6Ary.value.forEach(item1 => {
        if(item.tagValue == '纯跑ipv6'){
          Object.assign(ipv6, item1)
        }
      })
      payAry.value.forEach(item1 => {
        console.log(item1,item.tagValue, '异网支付')
        if (item.tagValue && item1.label && item.tagValue.includes(item1.label)) { 
          pay.value.push(item1)
        }
      })
    })
  }
}

getList()
</script>

<style scoped lang="scss">
.detail-item {
  display: flex;
  margin-bottom: 12px;
  align-items: center;
}

.detail-label {
  width: 150px;
  text-align: right;
  padding-right: 12px;
  line-height: 32px;
  font-size: 13px;
}

.detail-content {
  flex: 1;
  line-height: 32px;

  p {
    margin: 0;
    line-height: 22px;

    &:first-child {
      font-weight: bold;
      font-size: 13px;
    }

    &:last-child {
      font-size: 12px;
      color: #999;
    }
  }

  ul,
  li,
  ul li {
    margin: 0;
    padding: 0;
    list-style: none;
  }
}

.detail-container {
  background: #fafafa;
    padding-top: 20px;
}

:deep(.el-drawer__header) {
  margin-bottom: 0px;
  padding-bottom: 20px;
  border-bottom: 1px solid #dadada;
}

:deep(.el-radio-group) {
  vertical-align: middle;
  margin: 0 10px;
}

.header-tip {
  background: #fffbe6;
  border: 1px solid #ffe58f;
  padding: 10px 15px;

  p {
    margin: 0;
    font-size: 12px;
    color: #333;
    line-height: 19px;
  }

  b {
    font-weight: normal;
    color: #000;
    font-size: 13px;
    margin-bottom: 6px;
  }
}
</style>